#include <cstdlib>

#include <iostream>
#include <fstream>
#include <string>
#include <stdexcept>
#include "modx/ModuleLoader.h"
#include "modx/ModuleMixer.h"
#include "modx/ModulePlayer.h"

using namespace std;

int getChoice();
void waitOnReturnKey();
int main(int argc, char *argv[])
{
    ifstream* inputFile = NULL;
    modx::Module* moduleFile = NULL; 
	
	cout << "\t--ModuleConsole by Mre521--" << endl;
	
	if(argc < 3) {
		cout << "Invalid arguments:" << endl << "Usage: modulex inputfile outputfile" << endl;
		return 1;
	}
    
    try {
        inputFile = new ifstream(argv[1], ios::in | ios::binary);
    } catch(bad_alloc e) {
        cerr << "Bad allocation: " << e.what() << endl;
		return -1;
    }
    
    try {
        moduleFile = new modx::ModuleLoader(*inputFile);
    } catch(bad_alloc e) {
        cerr << "Bad allocation: " << e.what() << endl;    
		return -1;
    } catch(modx::LoaderException e) {
        cerr << "Loader exception: " << e.what() << endl;
		return -1;
    }
	
	ofstream out(argv[2], ios::out | ios::binary);
	modx::ModuleMixer mix(44100, 8);
	modx::ModulePlayer *play = new modx::ModulePlayer;
	short sndBuf[44100];
	int count = 0;
	long numRendered = 0;

	play->useModule(moduleFile);
	play->useMixer(&mix);
	play->play();
	
	for(count = 0; count < 120; count++) {
		numRendered = play->render(sndBuf, 44100);
		out.write((const char*)sndBuf, sizeof(short) * numRendered);
		
		if(numRendered < 44100) {
			break;
		}
	}

	
	out.close();
    delete moduleFile;
    inputFile->close(); delete inputFile;
	
    return EXIT_SUCCESS;
}

